<?php

namespace app\home\controller;

use app\common\controller\Home;
use think\Request;

//软删除的模型
use traits\mode\SoftDelete;

class Subject extends Home
{
   public $NoLogin = ['index','info','likes','play','callback'];  

   public function __construct()
   {
        parent::__construct();

        $this->SubjectModel = model('Subject.Subject');
        $this->TeacherModel = model('Teacher.Teacher');
        $this->CategoryModel = model('Subject.Category');
        $this->ChapterModel = model('Subject.Chapter');
        $this->CommentModel = model('Subject.Comment');
        $this->OrderModel = model('Subject.Order');
        $this->ReceiveModel = model('Coupon.Receive');
        $this->RecordModel = model('Business.Record');
        $this->BusinessModel = model('Business.Business');
        $this->CommissionModel = model('Business.Commission');
        $this->ColeectModel = model('Subject.Collect');
        $this->PayModel = model('Pay.Pay');
   }
       
    //课程搜索
    public function index()
    {   
        if($this->request->isAjax())
        {
            $page = $this->request->param('page',1,'trim');
            $limit = $this->request->param('limit',10,'trim');
            $keywords = $this->request->param('keywords','','trim');

            //偏移量
            $start = ($page-1)*$limit;

            $where = [];

            if(!empty($keywords))
            {
                $where['title'] = ['LIKE',"%$keywords%"];
            }

            //查询数据总条数
            $count = $this ->SubjectModel->where($where)->count();

            //查询数据
            $list = $this->SubjectModel
                         ->with(['category','teacher'])
                         ->where($where)
                         ->limit($start,$limit)
                         ->select();

            $data = [
                'count' => $count,
                'list'  => $list
            ];

            if($list)
            {
                //成功返回
                $this->success('返回列表',null,$data);
                exit;
            }else
            {
                //失败返回
                $this->error('暂无数据',null,$data);
                exit;
            }
        }
        return $this->view->fetch();
    }

    //课程详情页面
    public function info()
    {
        $subid = $this->request->param('subid',0,'trim');

        //判断课程信息是否存在
        $subject = $this->SubjectModel
                        ->with(['category'])
                        ->find($subid);

        if(!$subject)
        {
            $this->error('课程不存在');
            exit;
        }
        
        //为点赞状态设置一个属性并嵌入到课程资料中
        $subject['likes_active'] = false;

        //获取登录信息
        $login = $this->IsLogin(false);

        //判断是否已购买课程
        $buy = false;

        if($login)
        {
            $likes = isset($subject['likes']) ? trim($subject['likes']): '';
            $likes = explode(',',$likes);

            //增加自定义属性
            $subject['likes_active'] = in_array($login['id'],$likes) ? true : false;

            //查询当前用户是否有购买过
            $where = ['subid' =>$subid, 'busid'=>$login['id']];
            $check = $this->OrderModel->where($where)->find();
            $buy = $check ? true : false;

        }

        //查询章节
        $chapter = $this->ChapterModel->where(['subid'=>$subid])->select();
        
        //老师信息
        $teacherid = isset($subject['teacherid']) ? trim($subject['teacherid']) : 0;
        $teacher = $this->TeacherModel->find($teacherid);

        if($this->request->isAjax())
        {
            $page = $this->request->param('page',1,'trim');
            $limit = $this->request->param('limit',10,'trim');
            $keywords = $this->request->param('keywords','','trim');

            //偏移量
            $start = ($page-1)*$limit;

            $where = ['subid' => $subid];

            if(!empty($keywords))
            {
                $where['content'] = ['LIKE',"%$keywords%"];
            }

            //查询数据总条数
            $count = $this ->CommentModel->where($where)->count();

            //查询数据
            $list = $this->CommentModel
                         ->with(['business'])
                         ->where($where)
                         ->order('id desc')
                         ->limit($start,$limit)
                         ->select();

            $data = [
                'count' => $count,
                'list'  => $list
            ];

            if(!$list)
            {
                //成功返回
                $this->success('返回列表',null,$data);
                exit;
            }else
            {
                //失败返回
                $this->error('查询成功',null,$data);
                exit;
            }
        }

        $this->assign([ 
            'subject' => $subject,
            'chapter' => $chapter,
            'teacher' => $teacher,
            'buy'     => $buy,
        ]);

        return $this->view->fetch();

    }
    
    //课程点赞
    public function likes()
    {
        if($this->request->isAjax())
        {   
            //接收ajax请求发送过来的参数
            $subid = $this->request->param('subid',0,'trim');

            //利用模型把课程信息找出来
            $subject =$this->SubjectModel->find($subid);

            if(!$subject)
            {
                $this->error('课程不存在');
                exit;
            }

            //判断是否有登录
            $login = $this->isLogin(false);

            if(!$login)
            {
                $this->error('请先登录');
                exit;
            }

            $likes = isset($subject['likes']) ? trim($subject['likes']) : '';
            $likes = explode(',',$likes);
            $action = '';
            $msg = '';

            //in_array()方法查看对应id是否存在于$likes中
            //若存在则证明已经点过赞,若不存在则证明还未点赞

            if(in_array($login['id'],$likes))
            {
                //对于已经点过赞的用户，再次点击即视为取消点赞操作
                //即要把当前用户的id从点过赞的数组中去除掉
                $key = array_search($login['id'],$likes);
                
                //删除数组元素
                unset($likes[$key]);

                //将action设置为取消
                $action = 'cancel';

                //消息提醒
                $msg = '取消点赞';
            }else
            {
                //对于还未点赞的用户，则进行点赞操作
                $likes[] = $login['id'];

                //将action设置为accept
                $action = 'accept';

                //消息提醒
                $msg = '点赞成功';
               
            }
            $likes = array_filter($likes);//先去空
            $likes = array_unique($likes);//再保证唯一

            //implode(param1,param2)将数组元素以param1的形式组装成字符串
            //explode(param1,param2)将数组元素以param1的形式分割开来
            $data = [
                'id' => $subid,
                'likes' => implode(',',$likes)
            ];

            //更新语句
            //调用save()方法时传入了主键id，则此时save()方法执行的是更新语句，而不是插入一条新纪录的语句
            //将$data追加到$like数组中去
            $result = $this->SubjectModel->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error("{$msg}");
                exit;
            }else
            {
                $this->success("{$msg}",null,['action' => $action ]);
                exit;
            }
        }
    }

   // 课程收藏
   public function collect()
   {
       if($this->request->isAjax())
       {
           $subid = $this->request->param('subid', 0, 'trim');

           $subject = $this->SubjectModel->find($subid);

           if(!$subject)
           {
               $this->error('课程不存在');
               exit;
           }

           //判断是否有登录
           $login = $this->IsLogin(false);

           if(!$login)
           {
               $this->error('请先登录');
               exit;
           }

           $result = $action = $msg = '';

           //判断客户是否收藏
           $where = ['busid' => $login['id'], 'collectid' => $subid, 'status' => 'subject'];
           $collection = $this->CollectionModel->where($where)->find();
           
           if($collection)
           {
               //有收藏就取消收藏
               $result = $this->CollectionModel->where(['id' => $collection['id']])->delete();

               //取消动作
               $action = 'cancel';
               $msg = '取消收藏';
           }else
           {
               //没有收藏就添加收藏
               $data = [
                   'busid' => $login['id'],
                   'collectid' => $subid,
                   'status' => 'subject'
               ];

               $result = $this->CollectionModel->validate('common/Business/Collection')->save($data);
               
               $action = 'active';
               $msg = '收藏';
           }

           if($result === FALSE)
           {
               $this->error("{$msg}失败");
               exit;
           }else
           {
               $this->success("{$msg}成功", null, ['action' => $action]);
               exit;
           }
       }
   }

    //课程购买
    public function purchase() 
    {
        $subid = $this->request->param('subid', 0, 'trim');

        //查询一下课程是否存在
        $subject = $this->SubjectModel->with(['category', 'teacher'])->find($subid);

        if(!$subject)
        {
            $this->error('课程不存在');
            exit;
        }

        //查询当前这个人领取过的优惠券
        $where = [
            'busid' => $this->view->AutoLogin['id'],
            'receive.status' => '1'
        ];

        $coupon = $this->ReceiveModel->with(['coupon'])->where($where)->select();

        if($this->request->isPost())
        {
            $couid = $this->request->param('coupon', 0, 'trim');
            $pay = $this->request->param('pay', 'money', 'trim');
            $total = isset($subject['price']) ? trim($subject['price']) : 0;


            //查询是否有选择优惠券
            $where = ['receive.id' => $couid, 'receive.status' => '1'];
            $coupon = $this->ReceiveModel->with(['coupon'])->where($where)->find();

            if($coupon)
            {
                //获取到折扣率
                $rate = isset($coupon['coupon']['rate']) ? trim($coupon['coupon']['rate']) : 1;
                
                //两个高精度数字相乘
                $total = bcmul($total, $rate, 2);
            }

            //余额支付
            if($pay == "money")
            {
                // subject_order 用户订单表
                // business_record 用户消费记录
                // business 用户表
                // coupon_receive 优惠券领取记录表

                $this->OrderModel->startTrans();
                $this->RecordModel->startTrans();
                $this->BusinessModel->startTrans();
                $this->ReceiveModel->startTrans();
                $this->CommissionModel->startTrans();

                //插入订单表
                $OrderData = [
                    'subid' => $subid,
                    'busid' => $this->view->AutoLogin['id'],
                    'total' => $total,
                    'code' => build_code("ST"),
                    'pay' => 'money'
                ];

                //插入到订单表
                $OrderStatus = $this->OrderModel->validate('common/Subject/Order')->save($OrderData);

                if($OrderStatus === FALSE)
                {
                    $this->error($this->OrderModel->getError());
                    exit;
                }

                //消费记录
                $title = $subject['title'];
                $content = "购买了【{$title}】,花费了￥ $total 元";
                $RecordData = [
                    'total' => "-$total",
                    'content' => $content,
                    'busid' => $this->view->AutoLogin['id']
                ];

                $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

                if($RecordStatus === FALSE)
                {
                    $this->OrderModel->rollback();
                    $this->error($this->RecordModel->rollback());
                    exit;
                }

                //如果是余额支付就需要更新用户余额字段
                //减去消费的金额 剩下的余额
                $money = bcsub($this->view->AutoLogin['money'], $total);

                $BusinessData = [
                    'id' => $this->view->AutoLogin['id'],
                    'money' => $money
                ];

                $validate = [
                    [
                        'money' => ['number', 'egt:0'],
                    ],
                    [
                        'money.number'  => '余额必须是数字类型',
                        'money.egt'      => '余额不足请先充值',
                    ]
                ];

                $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

                if($BusinessStatus === FALSE)
                {
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                //如果有选择优惠券那么就要更新优惠券使用状态
                if($coupon)
                {
                    $ReceiveData = [
                        'id' => $couid,
                        'status' => '0'
                    ];

                    $ReceiveStatus = $this->ReceiveModel->isUpdate(true)->save($ReceiveData);

                    if($ReceiveStatus === FALSE)
                    {
                        $this->BusinessModel->rollback();
                        $this->RecordModel->rollback();
                        $this->OrderModel->rollback();
                        $this->error('优惠券状态更新失败');
                        exit;
                    }
                }

                //判断是否有推荐人可以得到佣金
                $parentid = $this->view->AutoLogin['parentid'] ? trim($this->view->AutoLogin['parentid']) : 0;
                $parent = $this->BusinessModel->find($parentid);
                if($parent)
                {
                    //佣金比率
                    $AmountRate = config('site.AmountRate') ? config('site.AmountRate') : 0.05;
                    
                    //消费金额*佣金比率 = 转给推荐人
                    $amount = bcmul($total, $AmountRate);

                    //插入佣金记录
                    $CommissionData = [
                        'orderid' => $this->OrderModel->id, //获取插入最后一条的自增ID
                        'busid' => $this->view->AutoLogin['id'],
                        'parentid' => $parentid,
                        'type' => 'subject', //买课程的佣金
                        'stauts' => '0', //未提现
                        'amount' => $amount, //佣金
                    ];

                    $CommissionStatus = $this->CommissionModel->save($CommissionData);

                    if($CommissionStatus === FALSE)
                    {
                        $this->ReceiveModel->rollback();
                        $this->BusinessModel->rollback();
                        $this->RecordModel->rollback();
                        $this->OrderModel->rollback();
                        $this->error('推荐信息存储失败');
                        exit;
                    }
                }

                if($OrderStatus === FALSE || $RecordStatus === FALSE)
                {
                    $this->CommissionModel->rollback();
                    $this->ReceiveModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error('余额购买失败');
                    exit;
                }else
                {
                    $this->OrderModel->commit();
                    $this->RecordModel->commit();
                    $this->BusinessModel->commit();
                    $this->ReceiveModel->commit();
                    $this->CommissionModel->commit();
                    $this->success('购买课程成功', url('home/subject/info', ['subid' => $subid]));
                    exit;
                }
            }else
            {
                //微信支付 || 支付宝
                //携带一个自定义的参数过去
                $third = [
                    'busid' => $this->view->AutoLogin['id'],
                    'subid' => $subid,
                    'couid' => $couid,
                ];

                // 组装参数
                $data = [
                    'name' => '课程购买', //标题
                    'third' => $third, //传递的第三方的参数
                    'total' => $total, //订单原价充值的价格
                    'type' => $pay, //支付方式
                    'cashier' => 1, //是否需要收银台界面
                    'jump' => "/home/subject/info?subid=$subid&action=success", //订单支付完成后跳转的界面
                    'notice' => '/home/pay/subject',  //异步回调地址
                ];

                //调用模型中的支付方法
                $result = $this->PayModel->payment($data);

                echo $result;
                exit;
            }
        }
        
        $this->assign([
            'subject' => $subject,
            'coupon' => json_encode($coupon)
        ]);

        return $this->view->fetch();
    }

    //课程视频播放 
    public function play()
    {
        if($this->request->isAjax())
        {
            $cid = $this->request->param('cid', 0, 'trim');

            //查询一下这个章节是否存在
            $chapter = $this->ChapterModel->find($cid);

            if(!$chapter)
            {   
                $this->error('章节不存在,请先选择章节');
                exit;
            }

            //判断是否有登录
            $login = $this->IsLogin(false);

            if(!$login)
            {
                $this->error('请先登录');
                exit;
            }

            //查找当前用户是否购买过订单
            $where = [
                'subid' => $chapter['subid'],
                'busid' => $login['id']
            ];

            $order = $this->OrderModel->where($where)->find();

            if(!$order)
            {
                $this->error('请先购买课程');
                exit;
            }

            $this->success('返回章节的信息', null, $chapter['url_text']);
            exit;
        }
    }

}
